package com.example.demo.config;

import com.example.demo.model.User;
import com.example.demo.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

/**
 * 数据初始化器
 * 用于在应用启动时初始化测试数据
 */
@Component
public class DataInitializer implements CommandLineRunner {

    private final UserRepository userRepository;

    /**
     * 构造函数注入UserRepository
     * 
     * @param userRepository 用户数据访问层
     */
    @Autowired
    public DataInitializer(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    /**
     * 应用启动时执行的初始化方法
     * 
     * @param args 命令行参数
     */
    @Override
    public void run(String... args) {
        // 检查是否已有测试用户数据
        if (!userRepository.existsByUsername("admin")) {
            // 创建测试用户
            User admin = new User("admin", "admin123");
            userRepository.save(admin);
            System.out.println("已创建测试用户: admin/admin123");
        }
        
        if (!userRepository.existsByUsername("test")) {
            User test = new User("test", "test123");
            userRepository.save(test);
            System.out.println("已创建测试用户: test/test123");
        }
    }
}